import { getTeacherCourseList, addCourse } from "../../api/api.js";
Page({
    data: {
        courses: [],
        showModal: false,
        newCourseName: "",
    },
    onLoad() {
        this.loadCourses();
    },

    // 加载课程列表
    loadCourses() {
        const { role, userId } = wx.getStorageSync("userInfo");
        if (role === 1) {
            getTeacherCourseList(userId)
                .then((res) => {
                    console.log(res);
                    this.setData({
                        courses: res.data.map((item) => ({
                            courseId: item.courseId,
                            courseName: item.courseName,
                        })),
                    });
                    console.log(this.data.courses);
                })
                .catch((err) => {
                    console.error("获取教师课程列表失败:", err);
                    // 显示错误提示
                    wx.showToast({
                        title: "获取课程列表失败",
                        icon: "none",
                    });
                });
        }
    },

    // 显示添加课程弹窗
    showAddCourseModal() {
        this.setData({
            showModal: true,
            newCourseName: "", // 清空上次输入
        });
    },

    // 监听课程名称输入
    onCourseNameInput(e) {
        this.setData({
            newCourseName: e.detail.value,
        });
    },

    // 取消添加课程
    cancelAddCourse() {
        this.setData({
            showModal: false,
        });
    },

    // 确认添加课程
    confirmAddCourse() {
        const courseName = this.data.newCourseName.trim();
        if (!courseName) {
            wx.showToast({
                title: "请输入课程名称",
                icon: "none",
            });
            return;
        }

        const userInfo = wx.getStorageSync("userInfo");
        wx.showLoading({
            title: "添加中...",
        });

        // 调用添加课程API
        addCourse(courseName, userInfo.userId)
            .then((res) => {
                wx.hideLoading();
                wx.showToast({
                    title: "添加成功",
                    icon: "success",
                });
                this.setData({
                    showModal: false,
                });
                // 重新加载课程列表
                this.loadCourses();
            })
            .catch((err) => {
                wx.hideLoading();
                console.error("添加课程失败:", err);
                wx.showToast({
                    title: "添加失败，请重试",
                    icon: "none",
                });
            });
    },

    navigateToClassPage: function(e) {
        const courseId = e.currentTarget.dataset.courseid;
        wx.navigateTo({
            url: `/pages/class/class?courseId=${courseId}`,
        });
    },

    // 退出登录
    logout() {
        wx.clearStorageSync();
        wx.redirectTo({
            url: '/pages/login/login'
        });
    },
});